<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head>

<meta charset="utf-8">
<meta name="generator" content="quarto-1.2.198">

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">


<title>R语言医学数据科学入门 - 2&nbsp; 数据结构和类型</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
div.columns{display: flex; gap: min(4vw, 1.5em);}
div.column{flex: auto; overflow-x: auto;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
ul.task-list li input[type="checkbox"] {
  width: 0.8em;
  margin: 0 0.8em 0.2em -1.6em;
  vertical-align: middle;
}
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
  { counter-reset: source-line 0; }
pre.numberSource code > span
  { position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
  { content: counter(source-line);
    position: relative; left: -1em; text-align: right; vertical-align: baseline;
    border: none; display: inline-block;
    -webkit-touch-callout: none; -webkit-user-select: none;
    -khtml-user-select: none; -moz-user-select: none;
    -ms-user-select: none; user-select: none;
    padding: 0 4px; width: 4em;
    color: #aaaaaa;
  }
pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa;  padding-left: 4px; }
div.sourceCode
  {   }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span.al { color: #ff0000; font-weight: bold; } /* Alert */
code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */
code span.at { color: #7d9029; } /* Attribute */
code span.bn { color: #40a070; } /* BaseN */
code span.bu { color: #008000; } /* BuiltIn */
code span.cf { color: #007020; font-weight: bold; } /* ControlFlow */
code span.ch { color: #4070a0; } /* Char */
code span.cn { color: #880000; } /* Constant */
code span.co { color: #60a0b0; font-style: italic; } /* Comment */
code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */
code span.do { color: #ba2121; font-style: italic; } /* Documentation */
code span.dt { color: #902000; } /* DataType */
code span.dv { color: #40a070; } /* DecVal */
code span.er { color: #ff0000; font-weight: bold; } /* Error */
code span.ex { } /* Extension */
code span.fl { color: #40a070; } /* Float */
code span.fu { color: #06287e; } /* Function */
code span.im { color: #008000; font-weight: bold; } /* Import */
code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */
code span.kw { color: #007020; font-weight: bold; } /* Keyword */
code span.op { color: #666666; } /* Operator */
code span.ot { color: #007020; } /* Other */
code span.pp { color: #bc7a00; } /* Preprocessor */
code span.sc { color: #4070a0; } /* SpecialChar */
code span.ss { color: #bb6688; } /* SpecialString */
code span.st { color: #4070a0; } /* String */
code span.va { color: #19177c; } /* Variable */
code span.vs { color: #4070a0; } /* VerbatimString */
code span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */
</style>


<script src="site_libs/quarto-nav/quarto-nav.js"></script>
<script src="site_libs/quarto-nav/headroom.min.js"></script>
<script src="site_libs/clipboard/clipboard.min.js"></script>
<script src="site_libs/quarto-search/autocomplete.umd.js"></script>
<script src="site_libs/quarto-search/fuse.min.js"></script>
<script src="site_libs/quarto-search/quarto-search.js"></script>
<meta name="quarto:offset" content="./">
<link href="./03-tidy_data.html" rel="next">
<link href="./01-hello_data.html" rel="prev">
<script src="site_libs/quarto-html/quarto.js"></script>
<script src="site_libs/quarto-html/popper.min.js"></script>
<script src="site_libs/quarto-html/tippy.umd.min.js"></script>
<script src="site_libs/quarto-html/anchor.min.js"></script>
<link href="site_libs/quarto-html/tippy.css" rel="stylesheet">
<link href="site_libs/quarto-html/quarto-syntax-highlighting.css" rel="stylesheet" id="quarto-text-highlighting-styles">
<script src="site_libs/bootstrap/bootstrap.min.js"></script>
<link href="site_libs/bootstrap/bootstrap-icons.css" rel="stylesheet">
<link href="site_libs/bootstrap/bootstrap.min.css" rel="stylesheet" id="quarto-bootstrap" data-mode="light">
<script id="quarto-search-options" type="application/json">{
  "location": "sidebar",
  "copy-button": false,
  "collapse-after": 3,
  "panel-placement": "start",
  "type": "textbox",
  "limit": 20,
  "language": {
    "search-no-results-text": "No results",
    "search-matching-documents-text": "matching documents",
    "search-copy-link-title": "Copy link to search",
    "search-hide-matches-text": "Hide additional matches",
    "search-more-match-text": "more match in this document",
    "search-more-matches-text": "more matches in this document",
    "search-clear-button-title": "Clear",
    "search-detached-cancel-button-title": "Cancel",
    "search-submit-button-title": "Submit"
  }
}</script>

<link href="site_libs/pagedtable-1.1/css/pagedtable.css" rel="stylesheet">
<script src="site_libs/pagedtable-1.1/js/pagedtable.js"></script>


</head>

<body class="nav-sidebar floating">

<div id="quarto-search-results"></div>
  <header id="quarto-header" class="headroom fixed-top">
  <nav class="quarto-secondary-nav" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar" aria-controls="quarto-sidebar" aria-expanded="false" aria-label="Toggle sidebar navigation" onclick="if (window.quartoToggleHeadroom) { window.quartoToggleHeadroom(); }">
    <div class="container-fluid d-flex justify-content-between">
      <h1 class="quarto-secondary-nav-title"><span class="chapter-number">2</span>&nbsp; <span class="chapter-title">数据结构和类型</span></h1>
      <button type="button" class="quarto-btn-toggle btn" aria-label="Show secondary navigation">
        <i class="bi bi-chevron-right"></i>
      </button>
    </div>
  </nav>
</header>
<!-- content -->
<div id="quarto-content" class="quarto-container page-columns page-rows-contents page-layout-article">
<!-- sidebar -->
  <nav id="quarto-sidebar" class="sidebar collapse sidebar-navigation floating overflow-auto">
    <div class="pt-lg-2 mt-2 text-left sidebar-header">
    <div class="sidebar-title mb-0 py-0">
      <a href="./">R语言医学数据科学入门</a> 
        <div class="sidebar-tools-main">
    <a href="" title="Share" id="sidebar-tool-dropdown-0" class="sidebar-tool dropdown-toggle px-1" data-bs-toggle="dropdown" aria-expanded="false"><i class="bi bi-share"></i></a>
    <ul class="dropdown-menu" aria-labelledby="sidebar-tool-dropdown-0">
        <li>
          <a class="dropdown-item sidebar-tools-main-item" href="https://twitter.com/intent/tweet?url=|url|">
            <i class="bi bi-bi-twitter pe-1"></i>
          Twitter
          </a>
        </li>
        <li>
          <a class="dropdown-item sidebar-tools-main-item" href="https://www.facebook.com/sharer/sharer.php?u=|url|">
            <i class="bi bi-bi-facebook pe-1"></i>
          Facebook
          </a>
        </li>
    </ul>
</div>
    </div>
      </div>
      <div class="mt-2 flex-shrink-0 align-items-center">
        <div class="sidebar-search">
        <div id="quarto-search" class="" title="Search"></div>
        </div>
      </div>
    <div class="sidebar-menu-container"> 
    <ul class="list-unstyled mt-1">
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="./index.html" class="sidebar-item-text sidebar-link">Preface</a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="./intro.html" class="sidebar-item-text sidebar-link">Introduction</a>
  </div>
</li>
        <li class="sidebar-item sidebar-item-section">
      <div class="sidebar-item-container"> 
            <a class="sidebar-item-text sidebar-link text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-1" aria-expanded="true">Data things</a>
          <a class="sidebar-item-toggle text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-1" aria-expanded="true">
            <i class="bi bi-chevron-right ms-2"></i>
          </a> 
      </div>
      <ul id="quarto-sidebar-section-1" class="collapse list-unstyled sidebar-section depth1 show">  
          <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="./01-hello_data.html" class="sidebar-item-text sidebar-link"><span class="chapter-number">1</span>&nbsp; <span class="chapter-title">Hello data</span></a>
  </div>
</li>
          <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="./02-Data types.html" class="sidebar-item-text sidebar-link active"><span class="chapter-number">2</span>&nbsp; <span class="chapter-title">数据结构和类型</span></a>
  </div>
</li>
          <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="./03-tidy_data.html" class="sidebar-item-text sidebar-link"><span class="chapter-number">3</span>&nbsp; <span class="chapter-title">Tidy data</span></a>
  </div>
</li>
          <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="./04-data IO.html" class="sidebar-item-text sidebar-link"><span class="chapter-number">4</span>&nbsp; <span class="chapter-title">Data I/O</span></a>
  </div>
</li>
      </ul>
  </li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="./tips.html" class="sidebar-item-text sidebar-link">Tips</a>
  </div>
</li>
        <li class="sidebar-item">
  <div class="sidebar-item-container"> 
  <a href="./references.html" class="sidebar-item-text sidebar-link">References</a>
  </div>
</li>
    </ul>
    </div>
</nav>
<!-- margin-sidebar -->
    <div id="quarto-margin-sidebar" class="sidebar margin-sidebar">
        <nav id="TOC" role="doc-toc" class="toc-active">
    <h2 id="toc-title">Table of contents</h2>
   
  <ul>
  <li><a href="#数据结构" id="toc-数据结构" class="nav-link active" data-scroll-target="#数据结构"><span class="toc-section-number">2.1</span>  数据结构</a>
  <ul class="collapse">
  <li><a href="#向量" id="toc-向量" class="nav-link" data-scroll-target="#向量"><span class="toc-section-number">2.1.1</span>  向量</a></li>
  <li><a href="#其他数据结构" id="toc-其他数据结构" class="nav-link" data-scroll-target="#其他数据结构"><span class="toc-section-number">2.1.2</span>  其他数据结构</a></li>
  <li><a href="#再次理解rectangular-data" id="toc-再次理解rectangular-data" class="nav-link" data-scroll-target="#再次理解rectangular-data"><span class="toc-section-number">2.1.3</span>  再次理解Rectangular Data</a></li>
  <li><a href="#数据类型" id="toc-数据类型" class="nav-link" data-scroll-target="#数据类型"><span class="toc-section-number">2.1.4</span>  数据类型</a></li>
  <li><a href="#统计学角度理解数据类型" id="toc-统计学角度理解数据类型" class="nav-link" data-scroll-target="#统计学角度理解数据类型"><span class="toc-section-number">2.1.5</span>  统计学角度理解数据类型</a></li>
  </ul></li>
  </ul>
</nav>
    </div>
<!-- main -->
<main class="content" id="quarto-document-content">

<header id="title-block-header" class="quarto-title-block default">
<div class="quarto-title">
<h1 class="title d-none d-lg-block"><span class="chapter-number">2</span>&nbsp; <span class="chapter-title">数据结构和类型</span></h1>
</div>



<div class="quarto-title-meta">

    
  
    
  </div>
  

</header>

<div class="cell">

</div>
<p>请记住，Python和R是面向对象（object）的语言，你看到的任何数据，都可以理解为是一个<strong>对象</strong>。</p>
<p>学语言，一般都会学习语言的数据结构，这是老生常谈。目前看了很多教程，总觉得说的又多又乱，在这里我还是为大家梳理一下。</p>
<section id="数据结构" class="level2" data-number="2.1">
<h2 data-number="2.1" class="anchored" data-anchor-id="数据结构"><span class="header-section-number">2.1</span> 数据结构</h2>
<div class="callout-tip callout callout-style-default callout-captioned">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-caption-container flex-fill">
Tip
</div>
</div>
<div class="callout-body-container callout-body">
<p>我们要从大到小一步一步来描述和理解数据。</p>
</div>
</div>
<p>我们看到一个对象（变量），首先要知道它是什么样的容器（数据结构），然后再看里面装了什么（数据值）。比如，你看到一个瓶子（结构），里面装了水（值）。</p>
<section id="向量" class="level3" data-number="2.1.1">
<h3 data-number="2.1.1" class="anchored" data-anchor-id="向量"><span class="header-section-number">2.1.1</span> 向量</h3>
<p>下面，我们看看R中，最基本的数据类型，向量（vector）。</p>
<p>在这段代码中，</p>
<ul>
<li><code>a</code>是矩阵（结构），里面有6个数字（11-16）。</li>
<li><code>b</code>是列表（结构），但它也认为其实是向量（vector），里面装的内容五花八门。</li>
<li><code>A</code>是把通过<code>as.vector()</code>函数，将矩阵转化成了向量。</li>
<li><code>c</code>就是一个普通的向量</li>
</ul>
<div class="cell">
<div class="sourceCode cell-code" id="cb1"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a>a <span class="ot">&lt;-</span> <span class="fu">matrix</span>(<span class="dv">11</span><span class="sc">:</span><span class="dv">16</span>, <span class="at">nrow=</span><span class="dv">3</span>, <span class="at">ncol=</span><span class="dv">2</span>)</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>b <span class="ot">&lt;-</span> <span class="fu">list</span>(<span class="dv">1</span>,<span class="st">"dogs"</span>,cars, a)</span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a>c <span class="ot">&lt;-</span> <span class="dv">5</span></span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a>A <span class="ot">&lt;-</span> <span class="fu">as.vector</span>(a)</span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a><span class="fu">is.vector</span>(a)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] FALSE</code></pre>
</div>
<div class="sourceCode cell-code" id="cb3"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="fu">is.vector</span>(A)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] TRUE</code></pre>
</div>
<div class="sourceCode cell-code" id="cb5"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="fu">is.vector</span>(b)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] TRUE</code></pre>
</div>
<div class="sourceCode cell-code" id="cb7"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="fu">is.vector</span>(c)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] TRUE</code></pre>
</div>
</div>
<div class="callout-warning callout callout-style-default callout-captioned">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-caption-container flex-fill">
Warning
</div>
</div>
<div class="callout-body-container callout-body">
<p><code>vector</code>向量，作为R最基本的数据结构，就像哆啦A梦的口袋，什么都可以装，并且任何其他数据类型都可以转化为向量。</p>
</div>
</div>
</section>
<section id="其他数据结构" class="level3" data-number="2.1.2">
<h3 data-number="2.1.2" class="anchored" data-anchor-id="其他数据结构"><span class="header-section-number">2.1.2</span> 其他数据结构</h3>
<p>刚刚其实我们已经看到了R的三种数据结构，包括<code>list</code>、<code>matrix</code>和向量。我们可以用 <code>class()</code>函数查看一下</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb9"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a><span class="fu">class</span>(a)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "matrix" "array" </code></pre>
</div>
<div class="sourceCode cell-code" id="cb11"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a><span class="fu">class</span>(b)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "list"</code></pre>
</div>
</div>
<p>此外，R里面还有多维数组（<code>array</code>）,其实，刚刚看到的matrix其实也是属于二维数组（<code>array</code>）。下面我们还要重点介绍data.frame和类似数据框的对象，如前面提到的<code>tibble</code>和<code>data.table</code></p>
</section>
<section id="再次理解rectangular-data" class="level3" data-number="2.1.3">
<h3 data-number="2.1.3" class="anchored" data-anchor-id="再次理解rectangular-data"><span class="header-section-number">2.1.3</span> 再次理解Rectangular Data</h3>
<p>统计分析中最常见的原始数据形式是类似于数据库表或Excel数据表的形式。 这样形式的数据在R中叫做数据框(data.frame)。 数据框类似于一个矩阵，有行、列， 但各列允许有不同类型：数值型、因子、字符、日期时间等。 同一列的数据类型一般是相同的。 还是以esoph这个数据对象为例。</p>
<div class="cell">
<div class="cell-output-display">
<table class="table table-sm table-striped">
<caption>data.frame 表</caption>
<thead>
<tr class="header">
<th style="text-align: left;">agegp</th>
<th style="text-align: left;">alcgp</th>
<th style="text-align: left;">tobgp</th>
<th style="text-align: right;">ncases</th>
<th style="text-align: right;">ncontrols</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: left;">25-34</td>
<td style="text-align: left;">0-39g/day</td>
<td style="text-align: left;">0-9g/day</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">40</td>
</tr>
<tr class="even">
<td style="text-align: left;">25-34</td>
<td style="text-align: left;">0-39g/day</td>
<td style="text-align: left;">10-19</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">10</td>
</tr>
<tr class="odd">
<td style="text-align: left;">25-34</td>
<td style="text-align: left;">0-39g/day</td>
<td style="text-align: left;">20-29</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">6</td>
</tr>
<tr class="even">
<td style="text-align: left;">25-34</td>
<td style="text-align: left;">0-39g/day</td>
<td style="text-align: left;">30+</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">5</td>
</tr>
<tr class="odd">
<td style="text-align: left;">25-34</td>
<td style="text-align: left;">40-79</td>
<td style="text-align: left;">0-9g/day</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">27</td>
</tr>
<tr class="even">
<td style="text-align: left;">25-34</td>
<td style="text-align: left;">40-79</td>
<td style="text-align: left;">10-19</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">7</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>我们查看一下它的类型</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb13"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a><span class="fu">class</span>(esoph)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "data.frame"</code></pre>
</div>
</div>
<p>我们把它转化成其他的表格对象</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb15"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a><span class="fu">as_tibble</span>(esoph) <span class="sc">%&gt;%</span> <span class="co">#转化成tibble对象</span></span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a>  <span class="fu">class</span>()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "tbl_df"     "tbl"        "data.frame"</code></pre>
</div>
</div>
<div class="cell">
<div class="sourceCode cell-code" id="cb17"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a><span class="fu">as.data.table</span>(esoph) <span class="sc">%&gt;%</span> <span class="co">#转化成data.table对象</span></span>
<span id="cb17-2"><a href="#cb17-2" aria-hidden="true" tabindex="-1"></a>  <span class="fu">class</span>()</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "data.table" "data.frame"</code></pre>
</div>
</div>
<p>看上去，他们并没有区别，但在后面具体的操作上，会有一些差别，后面具体实践，我们再去理解。</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb19"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a><span class="fu">as.data.table</span>(esoph) <span class="sc">%&gt;%</span> <span class="co">#输出data.table</span></span>
<span id="cb19-2"><a href="#cb19-2" aria-hidden="true" tabindex="-1"></a>  <span class="fu">head</span>() <span class="sc">%&gt;%</span> </span>
<span id="cb19-3"><a href="#cb19-3" aria-hidden="true" tabindex="-1"></a>  knitr<span class="sc">::</span><span class="fu">kable</span>(<span class="at">caption =</span> <span class="st">"data.table 表"</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output-display">
<table class="table table-sm table-striped">
<caption>data.table 表</caption>
<thead>
<tr class="header">
<th style="text-align: left;">agegp</th>
<th style="text-align: left;">alcgp</th>
<th style="text-align: left;">tobgp</th>
<th style="text-align: right;">ncases</th>
<th style="text-align: right;">ncontrols</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: left;">25-34</td>
<td style="text-align: left;">0-39g/day</td>
<td style="text-align: left;">0-9g/day</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">40</td>
</tr>
<tr class="even">
<td style="text-align: left;">25-34</td>
<td style="text-align: left;">0-39g/day</td>
<td style="text-align: left;">10-19</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">10</td>
</tr>
<tr class="odd">
<td style="text-align: left;">25-34</td>
<td style="text-align: left;">0-39g/day</td>
<td style="text-align: left;">20-29</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">6</td>
</tr>
<tr class="even">
<td style="text-align: left;">25-34</td>
<td style="text-align: left;">0-39g/day</td>
<td style="text-align: left;">30+</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">5</td>
</tr>
<tr class="odd">
<td style="text-align: left;">25-34</td>
<td style="text-align: left;">40-79</td>
<td style="text-align: left;">0-9g/day</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">27</td>
</tr>
<tr class="even">
<td style="text-align: left;">25-34</td>
<td style="text-align: left;">40-79</td>
<td style="text-align: left;">10-19</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">7</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
<section id="数据类型" class="level3" data-number="2.1.4">
<h3 data-number="2.1.4" class="anchored" data-anchor-id="数据类型"><span class="header-section-number">2.1.4</span> 数据类型</h3>
<p>接下来，我们看看数据框（盒子）里面到底装的是什么。</p>
<p>我们刚刚看到，表格里面是一些数字、文字之类的。在R中将这些数据划分为这些类型</p>
<ul>
<li>Numeric (1.2, 5, 7, 3.14159)</li>
<li>Integer (1, 2, 3, 4, 5)</li>
<li>Complex (i + 4)</li>
<li>Logical (TRUE / FALSE)</li>
<li>Character (“a”, “apple”)</li>
<li>Factor (以后再探讨)</li>
</ul>
<p>我们可以看看，这个表格中每个列都是什么类型的数据。</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb20"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a><span class="fu">str</span>(esoph)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>'data.frame':   88 obs. of  5 variables:
 $ agegp    : Ord.factor w/ 6 levels "25-34"&lt;"35-44"&lt;..: 1 1 1 1 1 1 1 1 1 1 ...
 $ alcgp    : Ord.factor w/ 4 levels "0-39g/day"&lt;"40-79"&lt;..: 1 1 1 1 2 2 2 2 3 3 ...
 $ tobgp    : Ord.factor w/ 4 levels "0-9g/day"&lt;"10-19"&lt;..: 1 2 3 4 1 2 3 4 1 2 ...
 $ ncases   : num  0 0 0 0 0 0 0 0 0 0 ...
 $ ncontrols: num  40 10 6 5 27 7 4 7 2 1 ...</code></pre>
</div>
</div>
<p>由于数据类型的文章属于太基础的知识，很多人写了太多文章，这里我就不赘述了。想继续深入了解的移步</p>
<p><a href="https://bookdown.org/wangminjie/R4DS/baseR-vectors.html">第 4 章 向量 | 数据科学中的 R 语言</a></p>
<p><a href="https://www.rforecology.com/post/data-types-in-r/">R Data types 101, or What kind of data do I have? | R (for ecology)</a></p>
<p>数据类型也像数据结构那样，可以转变的，比如，我们把表格中<code>alcgp</code>这一列转化成<code>character</code>。</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb22"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb22-1"><a href="#cb22-1" aria-hidden="true" tabindex="-1"></a>esoph<span class="sc">$</span>alcgp <span class="ot">&lt;-</span>  <span class="fu">as.character</span>(esoph<span class="sc">$</span>alcgp)</span>
<span id="cb22-2"><a href="#cb22-2" aria-hidden="true" tabindex="-1"></a><span class="fu">str</span>(esoph)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output cell-output-stdout">
<pre><code>'data.frame':   88 obs. of  5 variables:
 $ agegp    : Ord.factor w/ 6 levels "25-34"&lt;"35-44"&lt;..: 1 1 1 1 1 1 1 1 1 1 ...
 $ alcgp    : chr  "0-39g/day" "0-39g/day" "0-39g/day" "0-39g/day" ...
 $ tobgp    : Ord.factor w/ 4 levels "0-9g/day"&lt;"10-19"&lt;..: 1 2 3 4 1 2 3 4 1 2 ...
 $ ncases   : num  0 0 0 0 0 0 0 0 0 0 ...
 $ ncontrols: num  40 10 6 5 27 7 4 7 2 1 ...</code></pre>
</div>
</div>
</section>
<section id="统计学角度理解数据类型" class="level3" data-number="2.1.5">
<h3 data-number="2.1.5" class="anchored" data-anchor-id="统计学角度理解数据类型"><span class="header-section-number">2.1.5</span> 统计学角度理解数据类型</h3>
<p>统计学角度，数据类型不同，则统计分析方法不同。我们可以参考这篇经典的统计学思维数据分类</p>
<p><a href="https://openintro-ims.netlify.app/data-hello.html#variable-types">Chapter 1 Hello data | Introduction to Modern Statistics</a></p>
<p>简单来说，有如下类型</p>
<ul>
<li><strong>Numeric</strong> Data that are expressed on a numeric scale.
<ul>
<li>Continuous Data that can take on any value in an interval. (Synonyms: interval, float, numeric)</li>
<li>Discrete Data that can take on only integer values, such as counts. (Synonyms: integer, count)</li>
</ul></li>
<li><strong>Categorical</strong> Data that can take on only a specific set of values representing a set of possible categories. (Synonyms: enums, enumerated, factors)
<ul>
<li>Binary A special case of categorical data with just two categories of values, e.g., 0/1, true/false. (Synonyms: dichotomous, logical, indicator, boolean)</li>
<li>nominal Categorical data that has no explicit ordering.</li>
<li>Ordinal Categorical data that has an explicit ordering. (Synonym: ordered factor)</li>
</ul></li>
</ul>
<div class="callout-note callout callout-style-default callout-captioned">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-caption-container flex-fill">
Note
</div>
</div>
<div class="callout-body-container callout-body">
<p>为什么统计学家要将表格数据这样分类，我们下面就要从tidy data这个难啃的骨头说起。</p>
</div>
</div>


</section>
</section>

</main> <!-- /main -->
<script id="quarto-html-after-body" type="application/javascript">
window.document.addEventListener("DOMContentLoaded", function (event) {
  const toggleBodyColorMode = (bsSheetEl) => {
    const mode = bsSheetEl.getAttribute("data-mode");
    const bodyEl = window.document.querySelector("body");
    if (mode === "dark") {
      bodyEl.classList.add("quarto-dark");
      bodyEl.classList.remove("quarto-light");
    } else {
      bodyEl.classList.add("quarto-light");
      bodyEl.classList.remove("quarto-dark");
    }
  }
  const toggleBodyColorPrimary = () => {
    const bsSheetEl = window.document.querySelector("link#quarto-bootstrap");
    if (bsSheetEl) {
      toggleBodyColorMode(bsSheetEl);
    }
  }
  toggleBodyColorPrimary();  
  const icon = "";
  const anchorJS = new window.AnchorJS();
  anchorJS.options = {
    placement: 'right',
    icon: icon
  };
  anchorJS.add('.anchored');
  const clipboard = new window.ClipboardJS('.code-copy-button', {
    target: function(trigger) {
      return trigger.previousElementSibling;
    }
  });
  clipboard.on('success', function(e) {
    // button target
    const button = e.trigger;
    // don't keep focus
    button.blur();
    // flash "checked"
    button.classList.add('code-copy-button-checked');
    var currentTitle = button.getAttribute("title");
    button.setAttribute("title", "Copied!");
    let tooltip;
    if (window.bootstrap) {
      button.setAttribute("data-bs-toggle", "tooltip");
      button.setAttribute("data-bs-placement", "left");
      button.setAttribute("data-bs-title", "Copied!");
      tooltip = new bootstrap.Tooltip(button, 
        { trigger: "manual", 
          customClass: "code-copy-button-tooltip",
          offset: [0, -8]});
      tooltip.show();    
    }
    setTimeout(function() {
      if (tooltip) {
        tooltip.hide();
        button.removeAttribute("data-bs-title");
        button.removeAttribute("data-bs-toggle");
        button.removeAttribute("data-bs-placement");
      }
      button.setAttribute("title", currentTitle);
      button.classList.remove('code-copy-button-checked');
    }, 1000);
    // clear code selection
    e.clearSelection();
  });
  function tippyHover(el, contentFn) {
    const config = {
      allowHTML: true,
      content: contentFn,
      maxWidth: 500,
      delay: 100,
      arrow: false,
      appendTo: function(el) {
          return el.parentElement;
      },
      interactive: true,
      interactiveBorder: 10,
      theme: 'quarto',
      placement: 'bottom-start'
    };
    window.tippy(el, config); 
  }
  const noterefs = window.document.querySelectorAll('a[role="doc-noteref"]');
  for (var i=0; i<noterefs.length; i++) {
    const ref = noterefs[i];
    tippyHover(ref, function() {
      // use id or data attribute instead here
      let href = ref.getAttribute('data-footnote-href') || ref.getAttribute('href');
      try { href = new URL(href).hash; } catch {}
      const id = href.replace(/^#\/?/, "");
      const note = window.document.getElementById(id);
      return note.innerHTML;
    });
  }
  const findCites = (el) => {
    const parentEl = el.parentElement;
    if (parentEl) {
      const cites = parentEl.dataset.cites;
      if (cites) {
        return {
          el,
          cites: cites.split(' ')
        };
      } else {
        return findCites(el.parentElement)
      }
    } else {
      return undefined;
    }
  };
  var bibliorefs = window.document.querySelectorAll('a[role="doc-biblioref"]');
  for (var i=0; i<bibliorefs.length; i++) {
    const ref = bibliorefs[i];
    const citeInfo = findCites(ref);
    if (citeInfo) {
      tippyHover(citeInfo.el, function() {
        var popup = window.document.createElement('div');
        citeInfo.cites.forEach(function(cite) {
          var citeDiv = window.document.createElement('div');
          citeDiv.classList.add('hanging-indent');
          citeDiv.classList.add('csl-entry');
          var biblioDiv = window.document.getElementById('ref-' + cite);
          if (biblioDiv) {
            citeDiv.innerHTML = biblioDiv.innerHTML;
          }
          popup.appendChild(citeDiv);
        });
        return popup.innerHTML;
      });
    }
  }
});
</script>
<nav class="page-navigation">
  <div class="nav-page nav-page-previous">
      <a href="./01-hello_data.html" class="pagination-link">
        <i class="bi bi-arrow-left-short"></i> <span class="nav-page-text"><span class="chapter-number">1</span>&nbsp; <span class="chapter-title">Hello data</span></span>
      </a>          
  </div>
  <div class="nav-page nav-page-next">
      <a href="./03-tidy_data.html" class="pagination-link">
        <span class="nav-page-text"><span class="chapter-number">3</span>&nbsp; <span class="chapter-title">Tidy data</span></span> <i class="bi bi-arrow-right-short"></i>
      </a>
  </div>
</nav>
</div> <!-- /content -->



</body></html>